﻿@model XRM.Security.WebUI.Models.FileUploaderModel
@{ 
    string baseName = Model.BaseName; 
    string uploadUrl = Model.UploadUrl.Replace(@"\", @"\\");
}
<div>
    <article>
        <div id="@(baseName)_holder_file">
            <p id="@(baseName)_holder_info">Для загрузки перетащите файл в эту область<br />или</p>
            <p id="@(baseName)_upload_info"></p>
            <p id="@(baseName)_upload">
                <label id="@(baseName)_dad_not_supported_label" class="hidden">Drag & drop не поддерживается, но Вы можете загрузить файл<br/></label>
                <input type="file" style="display:inline;">
            </p>
        </div>
        <p id="@(baseName)_filereader" class="hidden">File API & FileReader API not supported</p>
        <p id="@(baseName)_formdata" class="hidden">XHR2's FormData is not supported</p>
        <p id="@(baseName)_progress" class="hidden">XHR2's upload progress isn't supported</p>
        <p id="@(baseName)_uploadprogress_cont" class="hidden">Прогрес: <progress id="@(baseName)_uploadprogress" min="0" max="100" value="0">0</progress></p>
    </article>
</div>

<script type="text/javascript">
    var @(baseName)_holder = document.getElementById('@(baseName)_holder_file'),
    @(baseName)_tests = {
        filereader: typeof FileReader != 'undefined',
        dnd: 'draggable' in document.createElement('span'),
        formdata: !!window.FormData,
        progress: "upload" in new XMLHttpRequest
    },
    @(baseName)_support = {
        filereader: document.getElementById('@(baseName)_filereader'),
        formdata: document.getElementById('@(baseName)_formdata'),
        progress: document.getElementById('@(baseName)_progress')
    },
    @(baseName)_progress = document.getElementById('@(baseName)_uploadprogress'),
    @(baseName)_progress_cont = document.getElementById('@(baseName)_uploadprogress_cont'),
    @(baseName)_holder_info = document.getElementById('@(baseName)_holder_info'),
    @(baseName)_fileupload = document.getElementById('@(baseName)_upload'),
    @(baseName)_upload_info = document.getElementById('@(baseName)_upload_info'),
    @(baseName)_dad_not_supported_label = document.getElementById('@(baseName)_dad_not_supported_label');

    "filereader formdata progress".split(' ').forEach(function (api) {
        if (@(baseName)_tests[api] === false) {
            @(baseName)_support[api].className = 'fail';
        } else {
            // FFS. I could have done el.hidden = true, but IE doesn't support
            // hidden, so I tried to create a polyfill that would extend the
            // Element.prototype, but then IE10 doesn't even give me access
            // to the Element object. Brilliant.
            @(baseName)_support[api].className = 'hidden';
        }
    });

    function @(baseName)_previewfile(file) {
        @(baseName)_holder_info.className = 'hidden';
        @if (Model.IsOneFile)
        {
            <text>@(baseName)_upload_info.innerHTML = '';</text>
        }
        @(baseName)_upload_info.innerHTML += '<p>Загружено ' + file.name + ' ' + (file.size ? (file.size / 1024 | 0) + 'K' : '');
        console.log(file);
    }

    function @(baseName)_readfiles(files) {
        var formData = @(baseName)_tests.formdata ? new FormData() : null;
        for (var i = 0; i < files.length; i++) {
            if (@(baseName)_tests.formdata) formData.append('file', files[i]);
            @(baseName)_previewfile(files[i]);
        }

        // now post a new XHR request
        if (@(baseName)_tests.formdata) {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '@(uploadUrl)');
            xhr.onload = function () {
                @(baseName)_progress.value = @(baseName)_progress.innerHTML = 100;
                @(baseName)_progress_cont.className = 'hidden';
            };

            if (@(baseName)_tests.progress) {
                xhr.upload.onprogress = function (event) {
                    if (event.lengthComputable) {
                        var complete = (event.loaded / event.total * 100 | 0);
                        @(baseName)_progress.value = @(baseName)_progress.innerHTML = complete;
                        @(baseName)_progress_cont.className = '';
                    }
                }
            }

            xhr.send(formData);
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    $("#@(baseName)UploadResult").val(xhr.responseText);
                    $("#@(baseName)UploadResult").change();
                }
            };
        }
    }

    @(baseName)_fileupload.querySelector('input').onchange = function () {
        @(baseName)_readfiles(this.files);
    };

    if (@(baseName)_tests.dnd) {
        @(baseName)_holder.ondragover = function () { this.className = 'hover'; return false; };
        @(baseName)_holder.ondragend = function () { this.className = ''; return false; };
        @(baseName)_holder.ondrop = function (e) {
            this.className = '';
            e.preventDefault();

            @if (Model.IsOneFile)
            {
                <text>
                if (e.dataTransfer.files.length > 1) {
                    alert('Разрешено загружать не более одного файла!');
                }
                else {
                    @(baseName)_readfiles(e.dataTransfer.files);
                }
                </text>
            }
            else {
                <text>
                @(baseName)_readfiles(e.dataTransfer.files);
                </text>
            }
        }
    } else {
        @(baseName)_dad_not_supported_label.className = '';
        @(baseName)_holder.className = 'hidden';
        @(baseName)_holder_info.className = 'hidden';
    }

    $("#@(baseName)UploadResult").change(function () {
        var result = $.parseJSON($(this).val());
        if (!result.isSuccess) {
            $("#@(baseName)UploadErrorMessage").html(result.error);
            $("#@(baseName)DataId").val();
        }
        else {
            $("#@(baseName)UploadErrorMessage").empty();
            $("#@(baseName)DataId").val(result.dataId);
        }
    });
</script>
<style type="text/css">
    #@(baseName)_holder_file { border: 5px dashed #ccc; width: 100%; min-height: 100px; margin-bottom: 7px;}
    #@(baseName)_holder_file.hover { border: 5px dashed #0c0; }
    #@(baseName)_holder_file img { display: block; margin: 10px auto; }
    #@(baseName)_holder_file p { margin: 10px; font-size: 14px; }
    #@(baseName)_holder_info, #@(baseName)_upload { text-align: center; }
</style>




